package top.kaoshanji.p2ch16a;

import top.kaoshanji.p2ch16a.support.NoEnoughMoneyException;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/26 17:16
 */
public class AccountMgr {

    // 代码清单-p2ch16a-477页a：使用 tryLock 尝试转账
    // 这里有两个 Account 对象，就是说，有两把锁
    public static boolean tryTransfer(Account form, Account to, double money) throws NoEnoughMoneyException {
        if (form.tryLock()) {
            try {
                if (to.tryLock()) {
                    try {
                        if (form.getMoney() >= money) {
                            // 账户A 向 账户B 转账
                            // 账户A 扣减、账户B 增加
                            form.reduce(money);
                            to.add(money);
                        } else {
                            throw new NoEnoughMoneyException();
                        }
                        return true;
                    } finally {
                        to.unLock();
                    }
                }
            } finally {
                form.unLock();
            }
        }
        return false;
    }



}
